﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.DataAccess;
using VehicleScale.Models;

namespace VehicleScale.Forms.Files
{
    public partial class FrmUpdateCustomers : TemplateForm
    {
        #region Ctors
        public FrmUpdateCustomers()
        {
            InitializeComponent();

            Initialize();


            this.BackColor = Setting.BackColor;
            this.uiGroupBox1.BackColor = Setting.BackColor;
            this.Size = new Common().SizeUpdate;

        }
        #endregion

        #region Singleton Members
        //private static volatile FrmUpdateCustomers instance;
        //private static object syncRoot = new Object();

        ///// <summary>
        ///// Create Instance
        ///// </summary>
        //public static FrmUpdateCustomers Instance
        //{
        //    get
        //    {
        //        lock (syncRoot)
        //        {
        //            if (instance == null)
        //                instance = new FrmUpdateCustomers();
        //        }

        //        return instance;
        //    }
        //}

        ///// <summary>
        ///// Free Instance
        ///// </summary>
        ///// <param name="e"></param>
        //protected override void OnClosed(EventArgs e)
        //{
        //    //instance = null;
        //    base.OnClosed(e);
        //}

        #endregion

        #region Field Members
        private bool _isEdit = false;
        private bool _isBinding = false;
        private ICustomerDataAccess _dataAccess = new CustomerDataAccess();
        #endregion

        #region Property Members
        private CustomerModel _customer = new CustomerModel();
        public CustomerModel Customer
        {
            get { return _customer; }
            set
            {
                if (_customer != value)
                {
                    _isEdit = true;
                    _customer = value;
                }
            }
        }

        private IList<CustomerModel> _collection;
        public IList<CustomerModel> Collection
        {
            set { _collection = value; }
        }
        #endregion

        #region Methods

        private void Initialize()
        {
            this.MaximizeBox = false;

            this.Load += new EventHandler(delegate
            {
                BindingControls();
                ValidatingControls();
            });
            this.btnSave.Click += new EventHandler(delegate { ClickButtonSave(); });
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
        }

        protected override void OnLoad(EventArgs e)
        {
            if (_isEdit)
                this.edtCustomerID.Enabled = false;
            base.OnLoad(e);
        }

        private void ResetBindingControls()
        {
            this.edtCustomerID.DataBindings.Clear();
            this.edtCustomerName.DataBindings.Clear();
            this.edtTelephone.DataBindings.Clear();
            this.edtFaxNumber.DataBindings.Clear();
            this.edtIdentification.DataBindings.Clear();
            this.edtTaxCode.DataBindings.Clear();
            this.edtAddress.DataBindings.Clear();
            this.edtDescription.DataBindings.Clear();
            this._isBinding = false;
        }
        private void BindingControls()
        {
            if (!_isBinding)
            {
                this.edtCustomerID.DataBindings.Add("Text", Customer, "CustomerID");
                this.edtCustomerName.DataBindings.Add("Text", Customer, "CustomerName");
                this.edtTelephone.DataBindings.Add("Text", Customer, "Telephone");
                this.edtFaxNumber.DataBindings.Add("Text", Customer, "FaxNumber");
                this.edtIdentification.DataBindings.Add("Text", Customer, "Identification");
                this.edtTaxCode.DataBindings.Add("Text", Customer, "TaxCode");
                this.edtAddress.DataBindings.Add("Text", Customer, "Address");
                this.edtDescription.DataBindings.Add("Text", Customer, "Description");
                _isBinding = true;
            }
        }
        private void ValidatingControls()
        {
            string errorMessage = String.Empty;
            this.edtCustomerName.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtCustomerName.Text) ?
                    ErrorException.Error("Họ tên khách hàng", errType.required) : String.Empty;
                errorProvider.SetError(this.edtCustomerName, errorMessage);
            });

            this.edtAddress.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtAddress.Text) ?
                    ErrorException.Error("Địa chỉ", errType.required) : String.Empty;
                errorProvider.SetError(this.edtAddress, errorMessage);
            });

            this.edtIdentification.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtIdentification.Text) ?
                    ErrorException.Error("CMND", errType.required) : String.Empty;
                errorProvider.SetError(this.edtIdentification, errorMessage);
            });

            this.edtIdentification.KeyPress += new KeyPressEventHandler(edtIdentification_KeyPress);
            this.edtTelephone.KeyPress += new KeyPressEventHandler(edtTelephone_KeyPress);
        }

        void edtTelephone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) &&
                e.KeyChar != Convert.ToChar(Keys.Back) &&
                e.KeyChar != '-')
            {
                e.Handled = true;
            }
        }

        void edtIdentification_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
            {
                e.Handled = true;
            }
        }
        #endregion

        #region Action Members

        /// <summary>
        /// Click button save
        /// </summary>
        private void ClickButtonSave()
        {
            bool invalidInput = false;

            foreach (Control ctrl in this.Controls)
            {
                if (errorProvider.GetError(ctrl) != String.Empty)
                {
                    invalidInput = true;
                    break;
                }
            }

            if (invalidInput)
            {
                Library.Tools.MsgBox.Show(Messages.ValidateInfoMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.errorProvider.Clear();

                _customer.ModifiedByID = Common.UserLogin.EmployeeID;
                _customer.ModifiedDate = DateTime.Now;

                bool result = false;
                if (!_isEdit)
                {
                    _customer.CreatedByID = Common.UserLogin.EmployeeID;
                    _customer.CreationDate = DateTime.Now;
                    result = _dataAccess.Add(_customer);

                    if (result)
                    {
                        Common.Customers.Add(_customer);
                        _collection.Add(_customer);
                        _customer = new CustomerModel() { Active = true };
                        ResetBindingControls();
                        BindingControls();
                        this.edtCustomerID.Focus();
                        try
                        {
                            LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Them moi khach hang : " + _customer.CustomerName);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        Library.Tools.MsgBox.Show(String.Format(Messages.NewFailedMessage, "khách hàng"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    result = _dataAccess.Edit(_customer);

                    if (result)
                    {
                        var query = (from c in Common.Customers
                                     where c.CustomerID == _customer.CustomerID
                                     select c).SingleOrDefault();
                        if (query != null)
                        {
                            _customer.CopyTo<CustomerModel>(query);
                        }
                        try
                        {
                            LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Thay doi khach hang : " + _customer.CustomerName);
                        }
                        catch
                        {
                        }
                        this.DialogResult = DialogResult.OK;

                        this.Close();
                    }
                    else
                    {
                        Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage, "khách hàng"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }


                }
            }
        }

        #endregion

    }
}
